using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebUpdaterAdminCore.Data;
using WebUpdaterAdminCore.Models;
using WebUpdaterAdminCore.Services;
using Microsoft.AspNetCore.Http;
using System.Threading;
using CSuperSocket.SocketBase.Config;
using System.Diagnostics;
using CSuperSocket.SocketEngine;
using WebUpdaterAdminCore.SocketServer;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace WebUpdaterAdminCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {            
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();
            services.AddSingleton<Providers.IWeatherProvider, Providers.WeatherProviderFake>();
            services.AddMvc();

            InitSocket(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                // Webpack initialization with hot-reload.
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true,
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "FileUploads")),
                RequestPath = "/FileUploads"
            });
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapSpaFallbackRoute(
                   name: "spa-fallback",
                   defaults: new { controller = "Home", action = "Index" });
            });

            var webSocketsOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 16 * 1024
            };
            app.UseWebSockets(webSocketsOptions);
        }

        private UpdaterSocketServerService _server;
       private void InitSocket(IServiceCollection service)
        {
            
            var setion = Configuration.GetSection("SimpleSocketConfig");
            var simpleCfg = setion.Get<SimpleSocketConfig>();

            Stopwatch startWatch = new Stopwatch();
            startWatch.Start();
            var bootstrap = BootstrapFactory.CreateBootstrapFromServerCfg(simpleCfg);

            startWatch.Stop();
            Console.WriteLine("CSpuerTcp初始化工厂耗时：{0}ms", startWatch.ElapsedMilliseconds);

            startWatch.Reset();
            startWatch.Start();
            var isSuccess = bootstrap.Initialize();
            startWatch.Stop();
            Console.WriteLine("CSpuerTcp启动耗时：{0}ms", startWatch.ElapsedMilliseconds);
            if (!isSuccess)
            {
                SetConsoleColor(ConsoleColor.Red);
                Console.WriteLine("Failed to initialize CSuperSocket ServiceEngine! Please check error log for more information!");                
                return;
            }
            _server = bootstrap.AppServers.ToList().FirstOrDefault() as UpdaterSocketServerService;
            Console.WriteLine("UpdaterSocketServerService Starting...");
            var result = bootstrap.Start();
            
            Console.WriteLine("监听端口:{0}", simpleCfg.Port);
            Console.WriteLine("-------------------------------------------------------------------");
            SetConsoleColor(ConsoleColor.Green);
            if(_server == null)
            {
                SetConsoleColor(ConsoleColor.Red);
                Console.WriteLine("初始化Socket Server失败");
                SetConsoleColor(ConsoleColor.White);

                return;
            }
            service.AddSingleton<UpdaterSocketServerService>(_server);
            //Console.WriteLine($"上位机唯一Id:{ConfigurationManager.AppSettings["Pid"].ToString()}");
        }
        private static bool _setConsoleColor;
        private static void SetConsoleColor(ConsoleColor color)
        {
            if (_setConsoleColor)
                Console.ForegroundColor = color;
        }
    }
}
